package org.raymond.iworks.study.mq.rabbitmq.classic.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author raymond
 * @version V1.0
 * @Description:
 */
@Slf4j
public class EmitLogDirect {
    public final static String EXCHANGE_NAME = "direct_logs";
    // args1. warning error
    // args2. info
    public static void main(String[] args) {
        send(args);
    }

    private static void send(String[] args){
        ConnectionFactory factory = factory();
        try(Connection conn = factory.newConnection();
            Channel channel = conn.createChannel()){
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            String severity = getSeverity(args);
            String message = getMessage(args);

            channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes(StandardCharsets.UTF_8));
            log.info("[x] sent: {}:{}", severity, message);
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }

    public static ConnectionFactory factory(){
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.125");
        factory.setPort(5672);
        return factory;
    }

    private static String getSeverity(String[] strings){
        if(strings.length<1) return "info";
        return strings[0];
    }

    private static String getMessage(String[] strings){
        if(strings.length<2) return "hello world";
        return joinStrings(strings, " ", 1);
    }

    private static String joinStrings(String[] strings, String delimiter, int startIndex){
        int length = strings.length;
        if(length==0) return "";
        if(length<=startIndex) return "";
        StringBuilder words = new StringBuilder(strings[startIndex]);
        for(int i=startIndex+1; i<length; i++){
            words.append(delimiter).append(strings[i]);
        }
        return words.toString();
    }
}
